var CA = {};
CA.typing = false;
/**
* Simulate typing: bs = Before Start
*/
CA.type = function(txt,bs,cb){
	var ed=CA.editor, count = 0, ts = 50, bs = bs || function(){}, cb = cb || function(){};
	(function(){
	if(!CA.typing){
		bs.call();
		CA.typing = true;
		(function(){
			//console.log("cotando... "+count);
			if(count==txt.length){
				CA.typing = false;
				cb.call();
				//return;
			}else{
				ed.insert(txt.charAt(count));
				count++;
				setTimeout(arguments.callee, ts);
			}
		})();
	}else{
		setTimeout(arguments.callee, ts);
	}
	})();
}
CA.log = function(){
	try{console.log.apply('',arguments);} catch(e) {}
}

CA.playList = [];
CA.playListIndex = 0;

CA.fillList = function(){
	$('#videoPlaylist li a').each(function(){
		CA.playList.push($(this).attr('href').replace('#',''));
	});
}

CA.showVideo = function(vName){
   try{
	CA.tutorial.player.cvideo = vName;
   	swfobject.embedSWF('http://www.youtube.com/v/'+vName+'&enablejsapi=1&rel=0&fs=1',
      		'videoContainer', '250', '250', '8', null, null,
      		{ allowScriptAccess: 'always', allowFullScreen: 'true', wmode: 'transparent'},
      		{ id: 'ytPlayer'});
   }catch(e){
		CA.log(e);
   }
}

$('#videoPlaylist li a:not(.selected)').click(function(e){
	e.preventDefault();
	e.stopPropagation();
	$('.selected').removeClass('selected');
	//just in case to continue from that video
	CA.playListIndex = $('#videoPlaylist li a').index($(this));
	CA.playVideo($(this).addClass('selected').attr('href').replace('#',''));
});

CA.onRenderVideo = function(){
	CA.fillList();
	CA.showVideo(CA.playList[CA.playListIndex]);
	$('#videoPlaylist li a').eq(CA.playListIndex).addClass('selected');
}

CA.playVideo = function(vName){
	var o = document.getElementById('ytPlayer');
	if(o){
		o.loadVideoById(vName);
		CA.tutorial.player.ctime = 0;
		CA.tutorial.player.ctask = 0;
		CA.tutorial.player.cvideo = vName;
		//CA.evalActions(vName);
	}
}

/* Youtube handlers*/
/*
function onPlayerError(errorCode) {
   CA.log("[YouTube] An error occured of type:" + errorCode);
}

function onPlayerStateChange(newState) {
	$("#playerState").html(newState);
	switch(newState){
		case 0:
			if(CA.playListIndex<CA.playList.length){
				CA.playListIndex++;
				$('#videoPlaylist li a').eq(CA.playListIndex).click();
			}
		break;
		case 1:
			if(!CA.tutorial.started){
				//first video
				CA.tutorial.player.cvideo = $('#videoPlaylist li a').eq(0).addClass('selected').attr('href').replace('#','');
				//CA.evalActions($('#videoPlaylist li a').eq(0).addClass('selected').attr('href').replace('#',''));
				CA.tutorial.started = true;
			}
		break;
		default:
		break;
	}	
}

function updatePlayerInfo(o) {
  // Also check that at least one function exists since when IE unloads the
  // page, it will destroy the SWF before clearing the interval.
  if(o && o.getDuration) {
	//CA.tutorial.player.ctime = o.getCurrentTime();
	//CA.callNextAction(o.getCurrentTime());

    $("#videoDuration").html(o.getDuration());
    $("#videoCurrentTime").html(o.getCurrentTime());
    $("#bytesTotal").html(o.getVideoBytesTotal());
    $("#startBytes").html(o.getVideoStartBytes());
    $("#bytesLoaded").html(o.getVideoBytesLoaded());
  }
}

function onYouTubePlayerReady(playerId)
{
    var o = document.getElementById('ytPlayer');
    if(o){
  		
		o.addEventListener("onStateChange", "onPlayerStateChange");
		o.addEventListener("onError", "onPlayerError");
		(function(){
			updatePlayerInfo(o);
			setTimeout(arguments.callee, '250');
		})(o);
    }
}
*/
/**
* Tutorial Functionality
*/

//Actions


CA.actions = {
	'openNewTab' : function(tabName){ },
	'showTab'    : function(tabIndex) { $('.tabs-list li').eq(tabIndex).find('.tab-tittle').click(); },
	'closeTab'   : function(tabIndex) { $('.tabs-list li').eq(tabIndex).find('.tab-close').click(); },
	'showConsole' : function(){ },
	'nLeft'  : function(){CA.editor.navigateLeft();}
}

CA.tutorial = {}; //namespace for the particular tutorial
CA.tutorial.started = false;
CA.tutorial.data = {
	//Video index is the main key
	'9iUvuaChDEg' : {
		'actions': [{
			'time': 0,
			'name' : 'wLines',
			'params':{
					"1": "function sample(){",
					"2": "    return 'crisboot is ROCK';",
					"3": "    //sample code by crisboot",
					"4": "    //There’s nothing to lose",
					"5": "    //When no one knows your name"
				}
			},{
			'time': 1,
			'name' : 'eval',
			'params': '$(".p-south .panel-header").click()'
			},{
			'time': 10,
			'name' : 'eval',
			'params': [
					'$("a.tab-tittle[href=#panel2]").click()',
					'$("input.browser-url").val("http://localhost/1")',
					'$("a.browser-go-btn").click()'
				]
			},{
			'time': 15,
			'name' : 'eval',
			'params': [
					'$("a.browser-prev-btn").click()',
					'setTimeout(function(){$("a.tab-tittle[href=#panel1]").click()},1000)'
				]
			},{
			'time': 20,
			'name': 'wLines',
			'params': {
					"6": "var alfa = "
				}
			
		}]
	},
	//video 2 actions
	'4XpnKHJAok8' : {
		'actions': [{
			'time': 0,
                        'name' : 'wLines',
			'params':{
					"6": "    function sample2(){",
					"7": "        return 'crisboot is ROCK';",
					"8": "        //sample code by crisboot",
					"9": "        //There’s nothing to lose",
					"10": "        //When no one knows your name"
				}
			}
		]
	}
};

CA.tutorial.player = {};
CA.tutorial.player.ctime = 0;
CA.tutorial.player.ctask = 0;
CA.tutorial.player.cvideo = '';
CA.tutorial.player.start = function(){};
CA.tutorial.player.stop = function(){};
CA.tutorial.player.next = function(){};

CA.callNextAction = function(cTime){
	if(typeof CA.tutorial.data[CA.tutorial.player.cvideo].actions[CA.tutorial.player.ctask] != 'undefined'){	
		console.log(cTime+' - '+CA.tutorial.data[CA.tutorial.player.cvideo].actions[CA.tutorial.player.ctask].time);

		if(cTime>CA.tutorial.data[CA.tutorial.player.cvideo].actions[CA.tutorial.player.ctask].time){
			CA.log("task"+CA.tutorial.player.ctask);
			 switch(CA.tutorial.data[CA.tutorial.player.cvideo].actions[CA.tutorial.player.ctask].name){
				case 'wLines':
					$.each(CA.tutorial.data[CA.tutorial.player.cvideo].actions[CA.tutorial.player.ctask].params, function(i,v){
						CA.type(v, function(){
							CA.editor.gotoLine(parseInt(i));
						},
						function(){
							CA.editor.splitLine();
							CA.editor.gotoLine(parseInt(i)+1);
						});
					});
				break;
				case 'eval':
					//alert(typeof CA.tutorial.data[CA.tutorial.player.cvideo].actions[CA.tutorial.player.ctask].params);
					switch(typeof CA.tutorial.data[CA.tutorial.player.cvideo].actions[CA.tutorial.player.ctask].params){
						case 'string':
							eval(CA.tutorial.data[CA.tutorial.player.cvideo].actions[CA.tutorial.player.ctask].params);
						break;
						case 'object':
							$.each(CA.tutorial.data[CA.tutorial.player.cvideo].actions[CA.tutorial.player.ctask].params,function(i,v){
								eval(v);
							});
						break;
						default:
						break;
					}
				break;
				default:
				break;
			}

			CA.tutorial.player.ctask++;
		}	
	}
}

CA.evalActions = function(videoId){
	if(typeof CA.tutorial.data[videoId] == 'object'){
		$.each(CA.tutorial.data[videoId].actions, function(a,t){//actions todo
			$.each(t, function(taskName,toResolve){
				switch(taskName){
					case 'wLines':
						$.each(toResolve, function(i,v){
							CA.type(v, function(){
								CA.editor.gotoLine(parseInt(i));
							},							
							function(){
								CA.editor.splitLine();
								CA.editor.gotoLine(parseInt(i)+1);
							});
						});
					break;
					case 'nLeft':
						CA.actions['nLeft'].call();
					break;
					default:	
					break;
				}
			});
		});
	}
}

/* Youtube handlers*/
function onPlayerError(errorCode) {
   CA.log("[YouTube] An error occured of type:" + errorCode);
}

function onPlayerStateChange(newState) {
        $("#playerState").html(newState);
        switch(newState){
                case 0:
                        if(CA.playListIndex<CA.playList.length){
                                CA.playListIndex++;
                                $('#videoPlaylist li a').eq(CA.playListIndex).click();
                        }
                break;
                case 1:
                        if(!CA.tutorial.started){
                                //first video
                                CA.tutorial.player.cvideo = $('#videoPlaylist li a').eq(0).addClass('selected').attr('href').replace('#','');
                                //CA.evalActions($('#videoPlaylist li a').eq(0).addClass('selected').attr('href').replace('#',''));
                                CA.tutorial.started = true;
                        }
                break;
                default:
                break;
        }
}

function updatePlayerInfo(o) {
  // Also check that at least one function exists since when IE unloads the
  // page, it will destroy the SWF before clearing the interval.
  if(o && o.getDuration) {
        //CA.tutorial.player.ctime = o.getCurrentTime();
        //CA.callNextAction(o.getCurrentTime());
	var ct = o.getCurrentTime();
	if(ct!=CA.tutorial.player.ctime){
		CA.tutorial.player.ctime = ct;
		CA.callNextAction(ct);
		//console.log(ct);
	}

    $("#videoDuration").html(o.getDuration());
    $("#videoCurrentTime").html(o.getCurrentTime());
    $("#bytesTotal").html(o.getVideoBytesTotal());
    $("#startBytes").html(o.getVideoStartBytes());
    $("#bytesLoaded").html(o.getVideoBytesLoaded());
  }
}

function onYouTubePlayerReady(playerId)
{
    var o = document.getElementById('ytPlayer');
    if(o){

                o.addEventListener("onStateChange", "onPlayerStateChange");
                o.addEventListener("onError", "onPlayerError");
                (function(){
                        updatePlayerInfo(o);
                        setTimeout(arguments.callee, '250');
                })(o);
    }
}


/**
* Editor
*/

/* 
lines = {
	"1": "function sample(){",
	"2": "    return 'crisboot is ROCK';",
	"3": "    //sample code by crisboot",
	"4": "    //There’s nothing to lose",
	"5": "    //When no one knows your name"
},*/
var startEditor = function() {
    CA.editor = ace.edit("editor");
    CA.editor.setTheme("ace/theme/twilight");
    
    var JavaScriptMode = require("ace/mode/javascript").Mode;
    CA.editor.getSession().setMode(new JavaScriptMode());
 	
	/*
    $.each(lines, function(i,v){
    	//console.log(parseFloat(i));
		//CA.editor.gotoLine(i);
		//setTimeout(function(){
		CA.type(v, function(){
			CA.editor.splitLine();
			CA.editor.gotoLine(parseInt(i)+1);
			//CA.editor.navigateDown();
		});
		//}, 3000)	
    });
	*/

    //Editor is laoded, now call the videos
    swfobject.addLoadEvent(CA.onRenderVideo);
}
